#!/bin/bash
# SchedulerAI Backend Container Startup Script

set -e

echo "Starting SchedulerAI Backend Service..."
echo "Timestamp: $(date)"
echo "Python version: $(python --version)"
echo "Working directory: $(pwd)"

# Validate environment variables
echo "Validating environment configuration..."

# Set default values if not provided
export API_HOST=${API_HOST:-0.0.0.0}
export API_PORT=${API_PORT:-8000}
export API_WORKERS=${API_WORKERS:-4}
export MAX_FILE_SIZE=${MAX_FILE_SIZE:-10485760}
export SOLVER_TIME_LIMIT=${SOLVER_TIME_LIMIT:-300}
export LOG_LEVEL=${LOG_LEVEL:-INFO}

echo "Configuration:"
echo "  API Host: $API_HOST"
echo "  API Port: $API_PORT"
echo "  Workers: $API_WORKERS"
echo "  Max File Size: $MAX_FILE_SIZE bytes"
echo "  Solver Time Limit: $SOLVER_TIME_LIMIT seconds"
echo "  Log Level: $LOG_LEVEL"

# Validate Python dependencies
echo "Validating Python dependencies..."
python -c "import ortools; print(f'OR-Tools version: {ortools.__version__}')" || {
    echo "ERROR: OR-Tools not found or not properly installed"
    exit 1
}

python -c "import fastapi; print(f'FastAPI version: {fastapi.__version__}')" || {
    echo "ERROR: FastAPI not found or not properly installed"
    exit 1
}

python -c "import pandas; print(f'Pandas version: {pandas.__version__}')" || {
    echo "ERROR: Pandas not found or not properly installed"
    exit 1
}

# Validate application modules
echo "Validating application modules..."
python -c "from scheduler_ai.simplified_api import app; print('API module loaded successfully')" || {
    echo "ERROR: Failed to load API module"
    exit 1
}

python -c "from scheduler_ai.simplified_scheduler_service import SimplifiedSchedulerService; print('Scheduler service loaded successfully')" || {
    echo "ERROR: Failed to load scheduler service"
    exit 1
}

# Create necessary directories
mkdir -p /app/uploads /app/data /app/logs

# Check port availability
if netstat -tuln | grep -q ":$API_PORT "; then
    echo "WARNING: Port $API_PORT appears to be in use"
fi

# Start the application with Gunicorn
echo "Starting Gunicorn server..."
exec gunicorn scheduler_ai.simplified_api:app \
    --bind $API_HOST:$API_PORT \
    --workers $API_WORKERS \
    --worker-class uvicorn.workers.UvicornWorker \
    --timeout 300 \
    --keep-alive 2 \
    --max-requests 1000 \
    --max-requests-jitter 50 \
    --preload \
    --access-logfile - \
    --error-logfile - \
    --log-level $(echo $LOG_LEVEL | tr '[:upper:]' '[:lower:]')